﻿/*
COPYRIGHT (C) 2011-2013 Raynald Messié

THIS FILE IS PART OF SCRUMPILOT.

SCRUMPILOT IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF 
THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

SCRUMPILOT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT
EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER
GENERAL PUBLIC LICENSE FOR MORE DETAILS.

YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH SCRUMPILOT. 
IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

using System.Globalization;
using System.Net;
using System.Web.Mvc;
using System.Web.Routing;
using ScrumPilot.Domain.BPL;
using ScrumPilot.Helpers;
using ScrumPilot.Models;
using ScrumPilot.TFSHelpers;

namespace ScrumPilot.Controllers
{
    public class AccountController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null)
            {
                // Test
                FormsService = new FormsAuthenticationService();
            }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            if (Session != null && Session["TFSNetCredential"] != null)
            {
                var ncd = Session["TFSNetCredential"] as NetworkCredential;
                if (ncd != null)
                {
                    return this.TFSLogon(ncd.UserName, ncd.Password, "", true);
                }
            }
            return (new ConfigServices()).GetConfig() == null
                       ? (ActionResult)RedirectToAction("InitialConfig", "Config")
                       : View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var result = this.TFSLogon(model.UserName, model.Password, returnUrl, model.RememberMe);
                if (result != null)
                    return result;
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        private ActionResult TFSLogon(string username, string password, string returnUrl, bool rememberMe)
        {
            var tfsUrl = SPHelpers.FormatTFSServerUrl();
            var tfs = new TFSServices(tfsUrl, username, password);
            if (tfs.Authenticate())
            {
                var userId = (new UserServices()).CheckIdentity(tfs.currentUser.Sid, false);

                FormsService.SignIn(userId.ToString(CultureInfo.InvariantCulture), rememberMe);
                Session["TFSServer"] = tfs;
                Session["TFSNetCredential"] = tfs.TFSNetCredential;
                return Url.IsLocalUrl(returnUrl)
                           ? (ActionResult)Redirect(returnUrl)
                           : RedirectToAction("Index", "Home");
            }
            return null;
        }


        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();
            Session["TFSNetCredential"] = null;
            return RedirectToAction("Index", "Home");
        }
    }
}